package edu.api.set_api;


import java.util.HashSet;
import java.util.Iterator;
import java.util.function.Consumer;

public class Demo {

    public static void main(String[] args) {
        test2();
    }

    /**
     * set保存自定义类对象，如果想根据对象的属性去重，需要重写equals和hashcode方法
     */
    public static void test2(){
        Product pd1 = new Product(4, "木糖醇", 10);
        Product pd2 = new Product(5, "洗发水", 12);
        Product pd3 = new Product(3, "热水壶", 49);
        Product pd4 = new Product(3, "热水壶", 49);
        System.out.println("pd3.equals(pd4) = " + pd3.equals(pd4));
        System.out.println("pd3.hashCode() == pd4.hashCode() = " + (pd3.hashCode() == pd4.hashCode()));
        HashSet<Product> products = new HashSet<>();
        products.add(pd1);
        products.add(pd2);
        products.add(pd3);
        products.add(pd4);
        for (Product product : products) {
            System.out.println(product);
        }
        System.out.println("-------------------------");
        //利用stream流对set排序
//        Set<Product> set = products.stream().sorted().collect(Collectors.toSet());
//        System.out.println("set = " + set);

    }


    public static void testFor() {
        HashSet<String> set = new HashSet<>();
        //添加
        set.add("Java程序设计");
        set.add("Java高级程序设计");
        set.add("spark开发");
        set.add("Hadoop");
        set.add("Java高级程序设计");
        //foreach
        for (String s : set) {
            System.out.println("s = " + s);
        }
        System.out.println("---------------------------------");

        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()){
            String s = iterator.next();
            System.out.println("s = " + s);
        }
        System.out.println("-------------------------------------");
        set.forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        });
    }


    public static void test() {
        HashSet<String> set = new HashSet<>();
        //添加
        set.add("Java程序设计");
        set.add("Java高级程序设计");
        set.add("spark开发");
        set.add("Hadoop");
        System.out.println("set = " + set);
        //判断是否包含
        boolean result = set.contains("Java程序设计");
        System.out.println("result = " + result);
        set.add("hadoop");
        int size = set.size();
        System.out.println("size = " + size);
    }

}
